package com.dianhun.multipledatasources.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * @author Administrator
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryAlert",
        transactionManagerRef = "transactionManagerAlert",
        basePackages = {"com.dianhun.multipledatasources.repository.alert"})
public class AlertDbConfig {
    @Autowired
    @Qualifier("alertDataSource")
    private DataSource alertDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    @Bean(name = "entityManagerAlert")
    public EntityManager entityManagerAlert(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryAlert(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryAlert")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryAlert(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(alertDataSource)
                .packages("com.dianhun.multipledatasources.model.alert")
                .persistenceUnit("alertPersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }

    @Bean(name = "transactionManagerAlert")
    public PlatformTransactionManager transactionManagerAlert(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryAlert(builder).getObject());
    }
}
